import type { Router } from 'vue-router'
import { initWalletStatus } from '@/dapp'
import { Toast } from 'vant'

export function setupRouterGuard(router: Router) {
  // createPageLoadingGuard(router)
  createScrollGuard(router)
  if (process.env.NODE_ENV === 'production') {
    createPermissionGuard(router)
  }
}

// Routing switch back to the top
function createScrollGuard(router: Router) {
  const body = document.getElementById('app')

  router.afterEach(async () => {
    // scroll top
    body?.scrollTo(0, 0)
    return true
  })
}
async function createPermissionGuard(router: Router) {
  router.beforeEach(async (to, from, next) => {
    let needToTrade = false
    // let initWalletLoading = false
    // 首页不进行连接
    if (!['/'].includes(to.path)) {
      // 只会执行一次，如果没有激活交给以后激活
      const res = await initWalletStatus(
        () => {
          history.pushState({}, '', to.path)
        },
        (e: any) => {
          // Toast.clear()
          Toast.fail(e)
          router.replace('/')
          history.replaceState({}, '', '/')
        },
      )
      needToTrade = res.needToTrade
      // initWalletLoading = res.initWalletLoading
    }
    // 加载中不做任何跳转
    // if (initWalletLoading) return

    if (needToTrade) {
      next('/trade')
    } else {
      next()
    }
  })
}
// export function createPageLoadingGuard(router: Router) {
//   let timeId: number
//   router.beforeEach(async (to) => {
//     if (to.meta.loaded) {
//       return true
//     }

//     timeId = (setTimeout as Window['setTimeout'])(() => {
//       Toast.loading({
//         // message: '加载中...',
//         forbidClick: true,
//         duration: 0,
//       })
//     }, 200)

//     return true
//   })

//   router.afterEach(async () => {
//     clearTimeout(timeId)
//     Toast.clear()
//     return true
//   })
// }
